package chat.network.http;

import com.whu.zj.MyApplication;
import com.whu.zj.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;


/**
 * 上传头像
 * Created by Administrator on 2016/1/11.
 */
public class UploadAvar {
    File file;
    String fileName;

    public UploadAvar(File file, String fileName) {
        this.file = file;
        this.fileName = fileName;
    }

    // 上传
    public boolean upload() throws Exception
    {
        HttpClient httpClient = new DefaultHttpClient();
        String IP = MyApplication.share().getResources().getString(R.string.IP);
        String url = "http://" + IP + "/chat/UploadAvar";
        HttpPost post = new HttpPost(url);
        MultipartEntityBuilder builder =  MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        builder.addTextBody("data", fileName, ContentType.TEXT_PLAIN.withCharset("utf-8"));

        builder.addBinaryBody("file", file);

        HttpEntity entity = builder.build();

        post.setEntity(entity);

        HttpResponse response = httpClient.execute(post);

        if(response.getStatusLine().getStatusCode() == 200)
        {
            System.out.println("HttpUrlUpload(uploadFile)文件上传成功！！！");
            return true;
        }
        System.out.println("HttpUrlUpload(uploadFile)文件上传失败！！！");
        return false;
    }
}
